//
//  MoviePlayer.m
//  MoviePlayer
//
//  Created by lanou on 15/11/6.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "MoviePlayer.h"

#import "Define.h"

@interface MoviePlayer ()<ProgressDelegate>
//如果不设置成属性 视频不能播放；


@property(nonatomic,strong)UIButton *play;//播放按钮；
@property(nonatomic,strong)UIView *topView;

@property(nonatomic,assign)BOOL isShow;
@end
@implementation MoviePlayer

//初始化方法；
- (instancetype)initWithFrame:(CGRect)frame URL:(NSURL *)url
{
    self = [super initWithFrame:frame];
    
    if (self)
    {
       
        self.moviePlayer = [[MPMoviePlayerController alloc]initWithContentURL:url];
        self.moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
        self.moviePlayer.view.frame = self.bounds;
        self.moviePlayer.view.backgroundColor = [UIColor whiteColor];
        self.view.backgroundColor = [UIColor whiteColor];
        //视频开始播放的时候 这个view 开始响应用户的操作 我们把他关闭 不让响应者链断裂；
        self.moviePlayer.view.userInteractionEnabled = NO;
        [self.moviePlayer play];
        
        //去除系统自带的控件；
        self.moviePlayer.controlStyle = MPMovieControlStyleNone;
        [self addSubview:self.moviePlayer.view];
        
        //顶部的View;
        self.topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
        //self.topView.backgroundColor = [UIColor blackColor];
        self.topView.alpha = 0.4;
        [self addSubview:self.topView];
        
        //顶部的label;
        self.topLabel = [[UILabel alloc]initWithFrame:CGRectMake((kScreenWidth-200)/2, 0, kScreenWidth-200, 30)];
        //self.topLabel.backgroundColor = [UIColor grayColor];
        self.topLabel.text = @"参观古老的城堡";
        self.topLabel.textColor = [UIColor whiteColor];
         
        self.topLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:self.topLabel];
        
        //创建我们的播放按钮
        self.play = [UIButton buttonWithType:UIButtonTypeCustom];
        self.play.frame = CGRectMake(0, 0, 45, 45);
        self.play.center = CGPointMake(frame.size.width/2, frame.size.height/2);
        [self.play setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        [self.play setImage:[UIImage imageNamed:@"play"] forState:UIControlStateSelected];
        //添加暂停播放方法；
        [self.play addTarget:self action:@selector(playMovie:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.play addTarget:self action:@selector(viewNoDismiss) forControlEvents:UIControlEventTouchUpInside];
        self.play.hidden = YES;
        [self addSubview:self.play];
        
        
        //创建下方显示进度条 时间显示控件；
        CGFloat height = 45;
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, frame.size.height - height, frame.size.width, 45)];
        //view.backgroundColor = [UIColor redColor];
        [self addSubview:view];
        view.hidden = YES;
        
        //创建我们的开始时间的label
        self.begin = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 60, height)];
        self.begin.text = @"00:00";
        self.begin.textColor = [UIColor whiteColor];
        self.begin.textAlignment = NSTextAlignmentCenter;
        [view addSubview:self.begin];
        
        //创建我们的进度条
        CGFloat progressX = self.begin.frame.size.width;
        self.progress = [[Progress alloc]initWithFrame:CGRectMake(progressX, 0, frame.size.width - progressX * 2, height)];
        
        [self.progress.slider addTarget:self action:@selector(valueChange:other:) forControlEvents:UIControlEventValueChanged];
        self.progress.cacheColor = [UIColor whiteColor];
        
        //设置代理；
         self.progress.delegate = self;
        [view addSubview:self.progress];
        
        
        //创建我们的总时长label;
        self.end = [[UILabel alloc]initWithFrame:CGRectMake(self.progress.frame.size.width+progressX, 0, progressX, height)];
        self.end.text = @"--:--";
        self.end.textColor = [UIColor whiteColor];
        self.end.textAlignment = NSTextAlignmentCenter;
        [view addSubview:self.end];
        self.view = view;//指针赋值；
        self.view.hidden = YES;
        
        //创建返回按钮
        _back = [UIButton buttonWithType:UIButtonTypeCustom];
        self.back.frame = CGRectMake(0, 0, frame.size.width*0.1, 30);
        //self.back.backgroundColor = [UIColor whiteColor];
        [self.back setImage:[UIImage imageNamed:@"3.png"] forState:UIControlStateNormal];
        [self addSubview:self.back];
        
        //接收我们的视频加载好后的通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(durationAvailable) name:MPMovieDurationAvailableNotification object:nil];
        
}
    return self;
    
}

//进度条滑动的时候执行的方法；
- (void)valueChange:(UISlider *)progress other:(UIEvent *)event
{
    //拿到我们的手指；
    UITouch *touch = [[event allTouches]anyObject];
    
    //保证视图不消失
    [self viewNoDismiss];
    switch (touch.phase)//phase是UITouch的一个属性；
    {
        case UITouchPhaseBegan:
        {
            break;
        }
        case UITouchPhaseMoved:
        {
            break;
        }
            case UITouchPhaseEnded:
        {
            //progress.touchInside
            //跳转到指定位置，进行播放；
            self.moviePlayer.currentPlaybackTime = progress.value;
            break;
        }
        default:
            break;
    }
    
}

//进度条的代理方法；
- (void)touchView:(float)value
{
    //跳转到指定位置
    self.moviePlayer.currentPlaybackTime = value;
    
}



//视频加载好之后执行的通知
- (void)durationAvailable
{
    //隐藏我们的返回按钮
    self.back.hidden = YES;
    
    
   // NSLog(@"%f",self.moviePlayer.duration);
    
    //给视频总时长赋值
    self.end.text = [self durationStringWithTime:(int)self.moviePlayer.duration];
    
    //修改progress的最大值和最小值；
    self.progress.slider.maximumValue = self.moviePlayer.duration;
    self.progress.slider.minimumValue = 0;
    
    //添加一个tap手势；在视频加载好之后添加轻拍手势；
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap2Action:)];
    [self.progress addGestureRecognizer:tap2];
    [self addGestureRecognizer:tap];
    
    //创建一个timer 时刻观察视频的状态；
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(playbackStatus:) userInfo:nil repeats:YES];

    
}

#pragma mark 视频状态的方法；
- (void)playbackStatus:(NSTimer *)timer
{
    //给我们的begin label和progress赋值；
    self.begin.text = [self durationStringWithTime:self.moviePlayer.currentPlaybackTime];
    //self.progress.value = self.moviePlayer.currentPlaybackTime;
    
    //缓冲进度条；
    self.progress.cache = self.moviePlayer.playableDuration;
    
    
    //当用户滑动滑块的时候我们不去赋值；
    if (self.progress.slider.touchInside == NO)
    {
        self.progress.slider.value = self.moviePlayer.currentPlaybackTime;
    }
    
    //NSLog(@"self.progress.value222 == %f",self.progress.value);

}



#pragma mark 根据时长求出字符串；
- (NSString *)durationStringWithTime:(int)time
{
    //获取分钟
    NSString *min = [NSString stringWithFormat:@"%02d",time/60];
    //获取秒数；
    NSString *s = [NSString stringWithFormat:@"%02d",time % 60];
    return [NSString stringWithFormat:@"%@:%@",min,s];
    
    
}

#pragma mark 视频暂停 播放的方法；
- (void)playMovie:(UIButton *)btn
{
    //selected默认是NO;
    btn.selected = !btn.selected;
    
    if (btn.selected)
    {
        //暂停
        [self.moviePlayer pause];
    }
    else
    {
        //播放；
        [self.moviePlayer play];
        
    }
    
}

- (void)tapAction
{
    [self viewNoDismiss];
    self.play.hidden = !self.play.hidden;
    self.view.hidden = !self.view.hidden;
    self.back.hidden = !self.back.hidden;
   
    if (!self.isShow)
    {
      [UIView animateWithDuration:1 animations:^{
        self.topView.frame = CGRectMake(0, 0, kScreenWidth, 0);
        //self.back.frame = CGRectMake(0, 0, kScreenWidth*0.1, 30);
        self.topLabel.frame = CGRectMake((kScreenWidth-200)/2, 0, kScreenWidth-200, 0);
        }];
  
    }
    else
    {
        [UIView animateWithDuration:1 animations:^{
            self.topView.frame = CGRectMake(0, 0, kScreenWidth, 30);
            //self.back.frame = CGRectMake(0, 0, kScreenWidth*0.1, 0);
            self.topLabel.frame = CGRectMake((kScreenWidth-200)/2, 0, kScreenWidth-200, 30);
        }];
        
    }
    self.isShow = !self.isShow;
    
}

- (void)tap2Action:(UITapGestureRecognizer *)tap
{
    
    CGPoint point = [tap locationInView:tap.view];
    self.progress.slider.value = point.x * (self.moviePlayer.duration)/self.progress.frame.size.width;
    self.moviePlayer.currentPlaybackTime = self.progress.slider.value;
   
    
}
#pragma mark 保证视图不消失的一个方法；每次调用这个方法 把之前的倒计时抹去 添加一个新的3s倒计时；

- (void)viewNoDismiss
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(dismiss) object:nil];
    
    
    [self performSelector:@selector(dismiss) withObject:nil afterDelay:3];
    

}

- (void)dismiss
{
    self.play.hidden = YES;
    self.view.hidden = YES;
    self.back.hidden = YES;
    
    [UIView animateWithDuration:1 animations:^{
        self.topView.frame = CGRectMake(0, 0, kScreenWidth, 0);
        //self.back.frame = CGRectMake(0, 0, kScreenWidth*0.1, 30);
        self.topLabel.frame = CGRectMake((kScreenWidth-200)/2, 0, kScreenWidth-200, 0);
    }];

}









@end
